package com.ruoyi.system.third.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.jeequan.jeepay.JeepayClient;
import com.jeequan.jeepay.exception.JeepayException;
import com.jeequan.jeepay.model.PayOrderCreateReqModel;
import com.jeequan.jeepay.model.RefundOrderCreateReqModel;
import com.jeequan.jeepay.request.PayOrderCreateRequest;
import com.jeequan.jeepay.request.RefundOrderCreateRequest;
import com.jeequan.jeepay.response.PayOrderCreateResponse;
import com.jeequan.jeepay.response.RefundOrderCreateResponse;
import com.ruoyi.common.utils.ParkingApiUtil;
import com.ruoyi.system.domain.TcyPlatformOrder;
import com.ruoyi.system.service.ITcyPlatformOrderService;
import com.ruoyi.system.third.constant.SysConstant;
import com.ruoyi.system.third.dto.PaymentDTO;
import com.ruoyi.system.third.dto.RefundDTO;
import com.ruoyi.system.third.service.ILiantuofuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
/**
 * @Description 联拓富请求服务
 * @Classname LiantuofuServiceImpl
 * @Date 2025-1-4 14:42
 * @Author 12601786
 */
@Service
public class LiantuofuServiceImpl implements ILiantuofuService {

    private static final Logger logger = LoggerFactory.getLogger(LiantuofuServiceImpl.class);

    @Resource
    private ITcyPlatformOrderService tcyPlatformOrderService;

    @Autowired
    private ParkingApiUtil parkingApiUtil;

//    @Override
//    public String transfer(JSONObject jsonObject, HttpServletRequest request) {
//        String uri = request.getHeader("uri");
//        String url = LIAN_TUO_FU_HOSTNAME + uri;
//        logger.info("liantuofu post api: [{}]", url);
//
//        if (null == jsonObject) {
//            jsonObject = JSONUtil.createObj();
//        }
//
//        jsonObject.set("random", ApiDemoSignUtil.getRandom());
//        if (StrUtil.isBlank(jsonObject.getStr("merchantCode"))) {
//            jsonObject.set("merchantCode", MERCHANT_CODE);
//        }
//        if (StrUtil.isBlank(jsonObject.getStr("appId"))) {
//            jsonObject.set("appId", APP_ID);
//        }
//        if (StrUtil.isBlank(jsonObject.getStr("key"))) {
//            jsonObject.set("sign", ApiDemoSignUtil.apiSign(jsonObject, KEY));
//        } else {
//            jsonObject.set("sign", ApiDemoSignUtil.apiSign(jsonObject, jsonObject.getStr("key")));
//        }
//
//        String result = HttpUtil.post(url, jsonObject);
//        logger.info("liantuofu post api result: [{}]", result);
//        return result;
//    }
//
//    @Resource
//    ISysUserService sysUserService;
//    @Resource
//    ISysConfigService configService;
//    @Override
//    public boolean syncMerchantList(SyncMerchantDTO syncMerchantDTO, HttpServletRequest request) {
//
//        JSONObject obj = JSONUtil.createObj();
//        obj.set("uri", "/open/merchant/list");
//
//        LoginUser loginUser = SecurityUtils.getLoginUser();
//        String appId = loginUser.getUser().getAppId();
//        String appKey = loginUser.getUser().getAppKey();
//
//        obj.set("appId", appId);
//        obj.set("key", appKey);
//
//        String result = this.getMerchantList(obj);
//
//        JSONObject jsonObject = JSONUtil.parseObj(result);
//        String code = jsonObject.getStr("code");
//        if (!StrUtil.equals("SUCCESS", code)) {
//            logger.error("/open/merchant/list is error! return code [{}]!", code);
//            return false;
//        }
//        List<MerchantInfoDTO> merchantInfoList = jsonObject.getBeanList("merchantList", MerchantInfoDTO.class);
//
//        Long deptId = syncMerchantDTO.getDeptId();
//        List<Long> roleIds = syncMerchantDTO.getRoleIds();
//
//        Long[] roleIdList = roleIds.toArray(new Long[0]);
////        List<MerchantInfoDTO> merchantInfoList = syncMerchantDTO.getMerchantInfoList();
//
//        for (MerchantInfoDTO merchantInfoDTO : merchantInfoList) {
//            String merchantCode = merchantInfoDTO.getMerchantCode();
//
//            SysUser user = sysUserService.selectUserByMerchantCode(merchantCode);
//            if (null == user) {
//                user = new SysUser();
//                user.setDeptId(deptId);
//                String merchantName = merchantInfoDTO.getMerchantName();
//                String merchantNameFirstLetter = PinyinUtil.getFirstLetter(merchantName, "");
//                user.setUserName(merchantNameFirstLetter + RandomUtil.randomNumbers(4));
//                user.setMerchantCode(merchantCode);
//                user.setNickName(merchantName);
//                user.setRoleIds(roleIdList);
//                user.setPhonenumber(merchantInfoDTO.getTelephone());
//                user.setAppId(appId);
//                user.setAppKey(appKey);
//                user.setUserType("01");
//                user.setFirstLoginFlag("0");
//                user.setPassword(SecurityUtils.encryptPassword(configService.selectConfigByKey("sys.user.initPassword")));
//                sysUserService.insertUser(user);
//            }
//        }
//        return true;
//    }

//    private String getMerchantList(JSONObject jsonObject) {
//        String url = LIAN_TUO_FU_HOSTNAME + jsonObject.get("uri");
//        logger.info("liantuofu post api: [{}]", url);
//
//        jsonObject.set("random", ApiDemoSignUtil.getRandom());
//        if (StrUtil.isBlank(jsonObject.getStr("merchantCode"))) {
//            jsonObject.set("merchantCode", MERCHANT_CODE);
//        }
//        if (StrUtil.isBlank(jsonObject.getStr("appId"))) {
//            jsonObject.set("appId", APP_ID);
//        }
//        if (StrUtil.isBlank(jsonObject.getStr("key"))) {
//            jsonObject.set("sign", ApiDemoSignUtil.apiSign(jsonObject, KEY));
//        } else {
//            jsonObject.set("sign", ApiDemoSignUtil.apiSign(jsonObject, jsonObject.getStr("key")));
//        }
//
//        String result = HttpUtil.post(url, jsonObject);
//        logger.info("liantuofu post api result: [{}]", result);
//        return result;
//    }

//    /**
//     * 联拓富支付
//     *
//     * @param paymentDTO
//     * @return
//     */
//    @Override
//    public String apiPayment(PaymentDTO paymentDTO) {
//        String outTradeNo = this.getOutTradeNo("P");
//        paymentDTO.setOutTradeNo(outTradeNo);
//
//        TcyPlatformOrder tcyPlatformOrder = BeanUtil.copyProperties(paymentDTO, TcyPlatformOrder.class);
//        //支付中
//        tcyPlatformOrder.setStatus("01");
//        tcyPlatformOrder.setPlatform("00");
//
//        tcyPlatformOrderService.insertTcyPlatformOrder(tcyPlatformOrder);
//
//        logger.info("paymentDTO:[{}]", paymentDTO);
//        String result = this.precreatePay(paymentDTO);
//        logger.info("precreatePay return result:[{}]", result);
//        JSONObject jsonObject = JSONUtil.parseObj(result);
//        String code = jsonObject.getStr("code");
//        if (!StrUtil.equals("SUCCESS", code)) {
//            logger.error("/open/precreate is error! return code [{}]!", code);
//            return "failure";
//        }
//
//        try {
//            tcyPlatformOrder.setStatus("02");
//            tcyPlatformOrder.setDiscountAmount(jsonObject.getBigDecimal("discountAmount", new BigDecimal(0)));
//
//            tcyPlatformOrderService.updateTcyPlatformOrder(tcyPlatformOrder);
//        } catch (Exception e) {
//            logger.error("updateTcyPlatformOrder is error!", e);
//            return "failure";
//        }
//        return "success";
//    }
//
//    private String precreatePay(PaymentDTO paymentDTO) {
//        LoginUser loginUser = SecurityUtils.getLoginUser();
//        String appId = loginUser.getUser().getAppId();
//        String appKey = loginUser.getUser().getAppKey();
//
//        JSONObject jsonObject = new JSONObject();
//
//        jsonObject.set("appId", appId);
//        jsonObject.set("random", ApiDemoSignUtil.getRandom());// 随机数
//        jsonObject.set("outTradeNo", paymentDTO.getOutTradeNo());// 订单号
//        jsonObject.set("totalAmount", paymentDTO.getTotalAmount()); // 支付总金额
//        jsonObject.set("channel", paymentDTO.getChannel()); // 支付渠道 WXPAY:微信 ALIPAY:支付宝 MPAY:会员 ;云闪付 UNIONPAY ;BESTPAY 翼支付 CASH现金
//        jsonObject.set("tradeType", paymentDTO.getTradeType()); // 交易类型 NATIVE:动态二维码 JSAPI:网页支付 MINIAPP:小程序
//        jsonObject.set("subAppId", paymentDTO.getSubAppId());
//        jsonObject.set("merchantCode", paymentDTO.getMerchantCode()); // 门店编码
//        jsonObject.set("openId", paymentDTO.getOpenId());
//        jsonObject.set("sign", ApiDemoSignUtil.apiSign(jsonObject, appKey));
//
//        return HttpUtil.post("http://api.liantuofu.com/open/precreate", jsonObject);
//    }

    private String getOutTradeNo(String type) {
        return "TCY-" + type + "-" + System.currentTimeMillis() + RandomUtil.randomNumbers(8);
    }


    @Override
    public String unifiedOrder(PaymentDTO paymentDTO) {
        String outTradeNo = this.getOutTradeNo("P");
        paymentDTO.setOutTradeNo(outTradeNo);

        TcyPlatformOrder tcyPlatformOrder = BeanUtil.copyProperties(paymentDTO, TcyPlatformOrder.class);
        //支付中
        tcyPlatformOrder.setStatus("01");
        tcyPlatformOrder.setPlatform("00");

        tcyPlatformOrderService.insertTcyPlatformOrder(tcyPlatformOrder);

        logger.info("paymentDTO:[{}]", paymentDTO);
        String result = this.unified(paymentDTO);
        if (StrUtil.equals("failure", result)) {
            logger.error("unifiedOrder is error! ");
            return "failure";
        }
        return result;
    }

    private String unified(PaymentDTO paymentDTO) {
        // 金额,元
        BigDecimal totalAmount = paymentDTO.getTotalAmount();
        // 如果直接使用分，那么则无需转换
        Long amount = totalAmount.multiply(new BigDecimal(100)).longValue();
        // 商户订单号
        String mchOrderNo = paymentDTO.getOutTradeNo();
//        String clientIP = jsonObject.getStr("machine_ip");
        // 订单标题
        String orderTitle = "支付测试";
//        String authCode = jsonObject.get("order_payment", JSONObject.class).getStr("scanned_code");

//        PayOrderCreateRequest request = new PayOrderCreateRequest();
//        PayOrderCreateReqModel model = new PayOrderCreateReqModel();
//
//        model.setMchNo(SysConstant.MCH_NO); // 商户号
//        model.setAppId(SysConstant.APP_ID);
//        model.setMchOrderNo(mchOrderNo);
//        model.setWayCode(paymentDTO.getTradeType());
//        model.setAmount(amount);
//        model.setCurrency("CNY");
////        model.setClientIp("192.166.1.132");
//        // 商品标题
//        model.setSubject(orderTitle + "[" + SysConstant.MCH_NO + "商户联调]");
//        model.setBody(orderTitle + "[" + SysConstant.MCH_NO + "商户联调]");
//        model.setNotifyUrl(SysConstant.NOTIFY_URL); //回调地址
//        model.setChannelExtra(channelExtra(paymentDTO.getTradeType(), paymentDTO.getOpenId()));
//        model.setExtParam("");
//        request.setBizModel(model);// 商户扩展参数,回调时原样返回

        JeepayClient jeepayClient = JeepayClient.getInstance(SysConstant.APP_ID, SysConstant.APP_SECRET, SysConstant.PAY_SITE_URL);
        String wayCode = "WX_LITE";                           // 支付方式
        PayOrderCreateRequest request = new PayOrderCreateRequest();
        PayOrderCreateReqModel model = new PayOrderCreateReqModel();
        model.setMchNo(SysConstant.MCH_NO);                       // 商户号
        model.setAppId(jeepayClient.getAppId());            // 应用ID
        model.setMchOrderNo(mchOrderNo);                       // 商户订单号
        model.setWayCode(paymentDTO.getTradeType());                          // 支付方式
        model.setAmount(amount);                                // 金额，单位分
        model.setCurrency("CNY");                           // 币种，目前只支持cny
        model.setClientIp("192.166.1.132");                 // 发起支付请求客户端的IP地址
        model.setSubject(paymentDTO.getSubject());                         // 商品标题
        model.setBody(paymentDTO.getBody());                            // 商品描述
        model.setNotifyUrl(SysConstant.NOTIFY_URL);      // 异步通知地址
        model.setReturnUrl("");                             // 前端跳转地址
        model.setChannelExtra(channelExtra(paymentDTO.getTradeType(), paymentDTO.getOpenId()));       // 渠道扩展参数
        model.setExtParam("");                              // 商户扩展参数,回调时原样返回

        request.setBizModel(model);

        try {
//            JeepayClient jeepayClient = JeepayClient.getInstance(SysConstant.APP_ID, SysConstant.APP_SECRET, SysConstant.PAY_SITE_URL);
            PayOrderCreateResponse response = jeepayClient.execute(request);
            if(response.getCode() != 0){
                logger.error("系统异常：[{}]", response.getMsg());
                return "failure";
            }
            //{"code":0,"data":{"mchOrderNo":"mho1743562582640","orderState":1,
            // "payData":"{\"timeStamp\":\"1743562583\",\"package\":\"prepay_id=wx0210562376812500fe66c08310a2250001\",
            // \"paySign\":\"wMyuJ4in+0J90yQ2zgMJUns4F0+lX4EIWgdVtlNbc8FH6/zDqBfsi+/zywL3QSdpU90CCt1JLySKPJWFhuGyYABkbIE/+BSnxbMkwK5zHQ0OE8ioDA3LD86XM1hR+z7mRzxIj4OZEKMMxwNnhOa9vw8OPKFUavQYfczkBDaldUiY9FAV/qxGkpnHUEdhGQq/tyTFXDPpMR4axaa2QMgwW47uTnnp7xPjZ8xC9CpJNr2AMsfE5TM84QybR9+zPOU1nO7aGTuPrhQ/hXBKm6rA3GB/iVcCa+nBMywfzFUnqd2Eq/m6QhT+mEsd/lDpzfqLeOfoU1/uXoxDbkipXDzIWA==\",\"appId\":\"wx86595b5f9ea5240c\",\"signType\":\"RSA\",\"nonceStr\":\"b8pAZLrW6u54xShccWwBxZIY8KYWkMYu\"}"
            // ,"payDataType":"wxapp","payOrderId":"P1907265828047503361"},"msg":"SUCCESS","sign":"E79834A89CBBA1B4ADC8B82F966437E6"}
            logger.info("系统支付正确，返回数据：[{}]", response);
            return response.toString();
            //{"payOrderId":"P1801211541071671298","mchOrderNo":"tcy_p_1718277270650","orderState":2,"payDataType":"none","payData":""}
        } catch (JeepayException e) {
            logger.error("系统异常：[{}]", e.getMessage());
        }
        return "failure";
    }

    /**
     * 退款
     *
     * @param refundDTO
     * @return
     */
    @Override
    public String refundOrder(RefundDTO refundDTO) {

        String outTradeNo = this.getOutTradeNo("R");
        refundDTO.setOutTradeNo(outTradeNo);

        TcyPlatformOrder tcyPlatformOrder = BeanUtil.copyProperties(refundDTO, TcyPlatformOrder.class);
        //支付中
        tcyPlatformOrder.setStatus("01");
        tcyPlatformOrder.setPlatform("00");

        tcyPlatformOrderService.insertTcyPlatformOrder(tcyPlatformOrder);

        logger.info("refundDTO:[{}]", refundDTO);
        boolean resultFlag = this.refund(refundDTO);
        if (!resultFlag) {
            logger.error("refundOrder is error! ");
            return "failure";
        }

        try {
            tcyPlatformOrder.setStatus("02");

            tcyPlatformOrderService.updateTcyPlatformOrder(tcyPlatformOrder);
        } catch (Exception e) {
            logger.error("updateTcyPlatformOrder is error!", e);
            return "failure";
        }
        return "success";
    }

    private boolean refund(RefundDTO refundDTO) {
       // 金额,元
        BigDecimal totalAmount = refundDTO.getTotalAmount();
        // 如果直接使用分，那么则无需转换
        Long refundAmount = totalAmount.multiply(new BigDecimal(100)).longValue();
        String payOrderId = refundDTO.getOrderSource();
        String mchRefundNo = refundDTO.getOutTradeNo();


        RefundOrderCreateRequest request = new RefundOrderCreateRequest();
        RefundOrderCreateReqModel model = new RefundOrderCreateReqModel();
        request.setBizModel(model);
        // 商户号
        model.setMchNo(SysConstant.MCH_NO);
        model.setAppId(SysConstant.APP_ID);
        model.setPayOrderId(payOrderId);
        model.setMchRefundNo(mchRefundNo);
        model.setRefundAmount(refundAmount);
        model.setRefundReason(refundDTO.getRefundReason());
        model.setCurrency("CNY");

        JeepayClient jeepayClient = new JeepayClient(SysConstant.PAY_SITE_URL, SysConstant.APP_SECRET);

        try {
            RefundOrderCreateResponse response = jeepayClient.execute(request);
            if(response.getCode() != 0){
                logger.error("系统异常：" + response.getMsg());
                return false;
            }
            System.out.println(JSON.toJSON(response.get()));
            return true;
        } catch (JeepayException e) {
            logger.error("系统异常：" + e.getMessage());
            return false;
        }
    }

    private String channelExtra(String wayCode, String param) {

        switch (wayCode) {
            case "WX_LITE" :
            case "WX_JSAPI" :
                return wxJsapiExtra(param);
            case "WX_BAR" : return wxBarExtra(param);
            case "ALI_BAR" : return aliBarExtra(param);
            case "YSF_BAR" : return ysfBarExtra(param);
            case "UPACP_BAR" : return upacpBarExtra(param);
            case "QR_CASHIER" : return qrCashierExtra(param);
            case "AUTO_BAR" : return autoBarExtra(param);
            case "PP_PC" : return ppExtra(param);
            case "SAND_H5" : return sandH5Extra(param);
            default: return "";
        }
    }

    private String wxJsapiExtra(String param) {
        JSONObject obj = new JSONObject();
        obj.put("openId", param);
//        obj.set("subAppId", "wx5d2b53d634cb78ff");
        return obj.toString();
    }

    private String wxBarExtra(String param) {
        JSONObject obj = new JSONObject();
        obj.put("authCode", "134675721924600802");
        return obj.toString();
    }

    private String aliBarExtra(String param) {
        JSONObject obj = new JSONObject();
        obj.put("authCode", "1180812820366966512");
        return obj.toString();
    }

    private String ysfBarExtra(String param) {
        JSONObject obj = new JSONObject();
        obj.put("authCode", "6223194037624963090");
        return obj.toString();
    }

    private String upacpBarExtra(String param) {
        JSONObject obj = new JSONObject();
        obj.put("authCode", "6227662446181058584");
        return obj.toString();
    }

    private String qrCashierExtra(String param) {
        JSONObject obj = new JSONObject();
        obj.put("payDataType", "codeImgUrl");
//        obj.put("payDataType", "payurl");
        return obj.toString();
    }

    private String autoBarExtra(String param) {
        JSONObject obj = new JSONObject();
        obj.put("authCode", "134753177301492386");
        return obj.toString();
    }

    private String ppExtra(String param) {
        JSONObject obj = new JSONObject();
        obj.put("cancelUrl", "http://baidu.com");
        return obj.toString();
    }

    private String sandH5Extra(String param) {
        JSONObject obj = new JSONObject();
        JSONObject payExtra = new JSONObject();
        // 聚合码
        obj.put("productCode", "02000001");
        obj.put("payExtra", "");
        obj.put("metaOption", "[{\"s\":\"Pc\",\"n\":\"支付\"}]");
        // 微信公众号
        /*obj.put("productCode", "02010002");
        payExtra = new JSONObject();
        payExtra.put("mer_app_id", "");
        payExtra.put("openid", "");
        obj.put("payExtra", payExtra.toString());
        obj.put("metaOption", "");
        // 微信小程序(云函数sdk)
        obj.put("productCode", "02010007");
        payExtra = new JSONObject();
        payExtra.put("wx_app_id", "");  // 移动应用Appid（微信开放平台获取，wx开头）
        payExtra.put("gh_ori_id", "");  // 小程序原始id（微信公众平台获取，gh_开头）
        payExtra.put("path_url", "");   // 拉起小程序页面的可带参路径，不填默认拉起小程序首页
        payExtra.put("miniProgramType", "0");   // 开发时根据小程序是开发版、体验版或正式版自行选择。正式版:0; 开发版:1; 体验版:2
        obj.put("payExtra", payExtra.toString());
        obj.put("metaOption", "");
        // 支付宝生活号
        obj.put("productCode", "02010002");
        payExtra = new JSONObject();
        payExtra.put("buyer_id", "");  // 支付宝生活号所需参数（支付宝H5建议不传）
        obj.put("payExtra", payExtra.toString());
        obj.put("metaOption", "");*/
        return obj.toString();

    }
}
